<?php
declare (strict_types=1);

namespace app\admin\middleware;

use app\admin\service\TokenService;
use think\Request;
use think\Response;

class Auth
{
    /**
     * 不需要权限的url
     *
     * @var string[]
     */
    protected $noAuthUrl = ['admin/user/captcha', 'admin/user/login', 'admin/user/logout'];

    /**
     * 当前url
     * @var
     */
    protected $currentPathInfo;

    /**
     * 处理请求，判断是否需要登录
     *
     * @param Request $request
     * @param \Closure $next
     * @return Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function handle(Request $request, \Closure $next): Response
    {
        $this->currentPathInfo = app('http')->getName() .'/'. $request->pathinfo();
        // 前置中间件
        if (!$this->checkToken() && !in_array($this->currentPathInfo, $this->noAuthUrl)) {
            return redirect('/admin/user/login?from=' . $this->currentPathInfo);
        }
        return $next($request);
    }

    /**
     * 校验token
     *
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function checkToken (): bool{
        $token = cookie("token");
        if (empty($token)) {
            return false;
        }
        return app()->make(TokenService::class)->checkToken($token);
    }
}
